
-- run 'xmake f -p cross --toolchain=gnu-rm --sdk=${GCC_DIR}'

set_warnings("everything")
set_languages("gnu11")

target("tkm32f499_demo")
    set_kind("binary")
    set_filename("tkm32f499_demo.elf")

    set_policy("check.auto_ignore_flags", false)

    -- set debug info
    set_symbols("debug")
    set_optimize("none")

    add_includedirs("CMSIS_and_startup", "CMSIS_and_startup/CMSIS")
    add_includedirs("Hal_lib/inc")
    add_includedirs("Code", "Code/Task/include")

    add_files("startup_tkm32f499.s", "CMSIS_and_startup/sys.c")
    add_files("Hal_lib/src/*.c")
    add_files("Code/**.c")

    del_files("Hal_lib/src/HAL_wwdg.c", "Hal_lib/src/HAL_iwdg.c", "Hal_lib/src/HAL_dma_bak.c")

    -- add FreeRTOS files
    add_includedirs("FreeRTOS/Source/include", "FreeRTOS/Source/include", "FreeRTOS/Source/portable/GCC/ARM_CM4F")
    add_files("FreeRTOS/Source/**.c")

    del_files("FreeRTOS/Source/portable/MemMang/heap_4.c")

    local mcu_defs = {"-mcpu=cortex-m4", "-mthumb", "-mfpu=fpv4-sp-d16", "-mfloat-abi=hard"}

    add_asflags(table.unpack(mcu_defs))

    add_cxflags(table.unpack(mcu_defs))

    add_ldflags(table.unpack(mcu_defs))
    add_ldflags("-TTKM32F499_FLASH.ld")

    add_ldflags("-Wl,-Map=build/target.map,--cref", "-Wl,--gc-sections")

    after_build(function (target)
        -- 获取ROM和RAM占用
        os.execv("arm-none-eabi-size", {target:targetfile()})

        -- 生成.list文件
        local outdata, errdata = os.iorunv("arm-none-eabi-objdump", {"-h", "-S", target:targetfile()})
        io.writefile("build/" .. target:name() .. ".list", outdata)

        -- 生成hex文件
        os.runv("arm-none-eabi-objcopy", {"-O", "ihex", target:targetfile(), "build/" .. target:name() .. ".hex"})

        -- 生成bin文件
        os.runv("arm-none-eabi-objcopy", {"-O", "binary", target:targetfile(), "build/" .. target:name() .. ".bin"})

        -- 复制elf文件到build/目录下
        os.cp(target:targetfile(), "build/")
    end)
